<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      auto-complete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title" v-if="loginType == 'register'">注册账号</h3>
        <h3 class="title" v-else>登录</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="请输入账号"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="请输入密码"
          name="password"
          tabindex="2"
          auto-complete="on"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon
            :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
          />
        </span>
      </el-form-item>
      <el-row>
        <el-col :span="16">
          <el-form-item prop="randCodeImage">
            <el-input
              placeholder="图片验证码"
              v-model="loginForm.inputCode"
              class="inputes"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6" class="img-warp">
          <img
            v-if="requestCodeSuccess"
            :src="randCodeImage"
            class="col_img"
            @click="handleChangeCheckCode"
          />
          <img
            v-else
            src="../../assets/login/checkcode.png"
            class="col_img"
            @click="handleChangeCheckCode"
          />
        </el-col>
      </el-row>

      <el-button
        v-if="loginType == 'register'"
        :loading="loading"
        type="primary"
        style="width: 100%; margin-bottom: 10px"
        @click.native.prevent="goRegister"
        >注册</el-button
      >

      <el-button
        v-else
        :loading="loading"
        type="primary"
        style="width: 100%; margin-bottom: 10px"
        @click.native.prevent="handleLogin"
        >登录</el-button
      >

      <p class="tips" v-if="loginType == 'register'">
        <span @click="handleRegister()" class="register"
          >注册好了，去登录>>></span
        >
      </p>
      <p class="tips" v-else>
        <span @click="handleRegister('register')" class="register"
          >冇账号，注册一个>>></span
        >
      </p>
    </el-form>
    <div class="copyright">
      <p class="content">
        Copyright © 2020.二手数据 All rights reserved.<br />
        <img
          src="http://img-blog.csdnimg.cn/20190410102033956.png"
          alt="网警"
          style="vertical-align: middle; line-height: 40px; height: 16px"
        /><a
          href="https://beian.miit.gov.cn"
          style="vertical-align: middle; line-height: 45px"
          target="_blank"
          >豫ICP备19015221号-1</a
        >
      </p>
    </div>
  </div>
</template>

<script>
import { randomImage, register } from "@/api/user.js";

export default {
  name: "Login",
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("请输入大于6位数的密码"));
      } else {
        callback();
      }
    };
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入账号"));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        username: "",
        password: "",
        inputCode: "",
        checkKey: "",
      },
      loginType: "",
      currTime: "",
      randCodeImage: null,
      requestCodeSuccess: false,

      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
      },
      loading: false,
      passwordType: "password",
      redirect: undefined,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },

  created() {
    this.handleChangeCheckCode();
  },

  methods: {
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },

    handleRegister(type) {
      this.loginType = type;
    },

    //获取图片验证码
    async handleChangeCheckCode() {
      this.currTime = new Date().getTime();
      this.loginForm.checkKey = new Date().getTime();
      this.inputCode = "";
      let res = await randomImage(this.currTime);
      if (res.data.success) {
        this.randCodeImage = res.data.result;
        this.requestCodeSuccess = true;
      } else {
        this.$message.error(res.data.message);
        this.requestCodeSuccess = false;
      }
    },

    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.$store
            .dispatch("user/login", this.loginForm)
            .then((res) => {
              if (res.data.code != 200) {
                this.$message.error(res.data.message);
                this.handleChangeCheckCode();
              } else {
                if (this.$store.state.app.query) {
                  let param = this.$store.state.app.query;
                  console.log("this.$store.state.app.query", param);
                  let key = Object.keys(param)[0];
                  this.$router
                    .push({
                      path: "/chart?" + key + "=" + param[key],
                    })
                    .then((res) => {
                      store.dispatch("app/setlastVisitRoute", null);
                    });
                  console.log("loginafter", store.state.app.query);
                } else {
                  this.$router.push({
                    path: "/chart?page=home",
                  });
                }
              }
              this.loading = false;
            })
            .catch((error) => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },

    goRegister() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          register({
            username: this.loginForm.username,
            password: this.loginForm.password,
            captcha: this.loginForm.inputCode,
            checkKey: this.loginForm.checkKey,
          }).then((response) => {
            const { data } = response;
            if (data.code != 200) {
              this.$message.error(data.message);
              this.handleChangeCheckCode();
            } else {
              this.$message.success(data.message);
            }
          });
        }
      });
    },
  },
};
</script>

<style lang="scss">
$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    // margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }

    .register {
      cursor: pointer;
      color: #409eff;
    }
  }

  .copyright {
    width: 100%;
    position: absolute;
    bottom: 0px;
    font-size: 12px;
    color: #6a6a6a;

    .content {
      text-align: center;
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .img-warp {
    position: absolute;
    right: 0;
    top: 5px;
    text-align: center;
    .col_img {
      height: 40px;
      width: 100%;
      background-size: 100% 100%;
      // position: absolute;
    }
  }
}
</style>
